package cn.wizzer.app.web.modules.controllers.user;

import cn.wizzer.app.sys.modules.models.SysCurrency;
import cn.wizzer.app.sys.modules.models.constant.CurrencyConstant;
import cn.wizzer.app.sys.modules.services.SysCurrencyService;
import cn.wizzer.app.user.modules.models.UserBankCard;
import cn.wizzer.app.user.modules.models.enums.BankCardTypeEnum;
import cn.wizzer.app.user.modules.services.UserBankCardService;
import cn.wizzer.app.web.commons.filter.ApiTokenFilter;
import cn.wizzer.app.web.commons.ulog.annotation.ULog;
import cn.wizzer.framework.base.model.enums.BizExceptionEnum;
import cn.wizzer.framework.util.Result;
import cn.wizzer.framework.util.param.ParamVerify;
import com.alibaba.dubbo.config.annotation.Reference;
import org.nutz.dao.Cnd;
import org.nutz.ioc.loader.annotation.Inject;
import org.nutz.ioc.loader.annotation.IocBean;
import org.nutz.lang.Strings;
import org.nutz.lang.Times;
import org.nutz.mvc.Mvcs;
import org.nutz.mvc.annotation.At;
import org.nutz.mvc.annotation.By;
import org.nutz.mvc.annotation.Filters;
import org.nutz.mvc.annotation.Ok;

import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
 * @author zl
 * @date 2020/8/25 16:06
 */
@IocBean
@At("/api/user/bank/card")
public class ApiUserBankCardController {

    @Inject
    @Reference
    private UserBankCardService userBankService;

    @Inject
    @Reference
    private SysCurrencyService sysCurrencyService;

    /**
     * 用户银行卡列表
     *
     * @param currencyId
     * @return
     */
    @At
    @Ok("json")
    @Filters({@By(type = ApiTokenFilter.class)})
    public Result list(String currencyId) {
        Cnd cnd = Cnd.where("userId", "=", Mvcs.getReq().getHeader("appid"))
                .and("c.delFlag", "=", 0).and("c.disabled", "=", 0);
        if (Strings.isNotBlank(currencyId)) {
            SysCurrency sysCurrency = sysCurrencyService.fetch(currencyId);
            if (!CurrencyConstant.INR.equals(sysCurrency.getName())) {
                cnd.and("b.currencyId", "=", currencyId).and("b.disabled", "=", 0);
            }
        }
        cnd.desc("c.ctAt");
        return Result.success().addData(userBankService.queryVO(cnd));
    }

    /**
     * 用户添加银行卡
     *
     * @param cardNumber  银行卡号码或印度UPI
     * @param accountName 账户名
     * @param bankId      系统银行库中银行id
     * @param phone       用户手机号
     * @param type        银行卡类型：BANKCARD(普通银行卡)、UPI(印度UPI)
     * @param IFSCCODE    印度银行IFSCCODE
     * @return
     */
    @At
    @Ok("json")
    @Filters({@By(type = ApiTokenFilter.class)})
    @ULog(tag = "用户添加银行卡", msg = "卡号: ${cardNumber}，账户名:${accountName}，系统银行库id:${bankId}")
    public Result add(@ParamVerify(required = true) String cardNumber,
                      @ParamVerify(required = true) String accountName,
                      @ParamVerify(required = false) String bankId,
                      @ParamVerify(required = true) String phone,
                      @ParamVerify(required = true) BankCardTypeEnum type,
                      @ParamVerify(required = false) String IFSCCODE
    ) {
        String appid = Mvcs.getReq().getHeader("appid");
        // 普通银行卡校验格式。印度UPIID可以是任意字符串无法校验。
        if (BankCardTypeEnum.BANKCARD.equals(type)) {
            //校验cardNumber 只能纯数字
            boolean result = cardNumber.matches("[0-9]+");
            if (!result) {
                return Result.error(BizExceptionEnum.BANK_CARD_ERROR);
            }
        }
        // 每个用户银行卡最多绑定十条
        int count = userBankService.count(Cnd.where("userId", "=", appid));
        if (count >= 10) {
            return Result.error(BizExceptionEnum.UP_TO_10_BANKCARDS_ARE_BOUND);
        }
        //region 验证已存在
        UserBankCard fetch = userBankService.fetch(Cnd.where("cardNumber", "=", cardNumber));
        if (fetch != null) {
            return Result.error(BizExceptionEnum.BANK_CARD_ALREADY_EXIST);
        }
        //endregion
        UserBankCard userBankCard = new UserBankCard();
        userBankCard.setCardNumber(cardNumber);
        userBankCard.setBankLibId(bankId);
        userBankCard.setAccountName(accountName);
        userBankCard.setUserId(appid);
        userBankCard.setPhone(phone);
        userBankCard.setType(type);
        if (Strings.isNotBlank(IFSCCODE)) {
            userBankCard.setIFSCCODE(IFSCCODE);
        }
        userBankService.insert(userBankCard);
        return Result.success();
    }

    // 暂时关闭功能
//    @At
//    @Ok("json")
//    @Filters({@By(type = ApiTokenFilter.class)})
//    @ULog(tag = "用户删除银行卡")
//    public Result del(@ParamVerify(required = true) String id) {
//        //验证银行卡
//        userBankService.verifyBankCard(id, Mvcs.getReq().getHeader("appid"));
//        UserBankCard userBankCard = userBankService.fetch(id);
//        userBankCard.setDisabled(true);
//        userBankCard.setOpAt(Times.getTS());
//        userBankService.update(userBankCard);
//        return Result.success();
//    }

}
